/* eslint-disable camelcase */
/* eslint-disable no-debugger */
import { ApiResponse, searchResult, Suggestion } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { Toast } from 'antd-mobile'

// 获取搜索建议
export const getSuggests = (keyword: string): RootThunkAction => {
  return async (dispatch) => {
    // <ApiResponse<{results: Article[], pre_timestamp: string}>>
    const res = await request.get<
      ApiResponse<{ options: Suggestion }>
    >('/suggestion', {
      params: {
        q: keyword
      }
    })
    console.log('获取搜索建议', res.data.data.options)

    dispatch({
      type: 'search/suggestion',
      payload: res.data.data.options
    })
  }
}

// 添加搜索历史记录
export const addHistory = (keyword: string): RootThunkAction => {
  return (dispatch, getState) => {
    let oldHistory = getState().search.searchHistory
    // 让搜索历史记录列表里的内容不能重复
    oldHistory = oldHistory.filter((item: string) => item !== keyword)
    const newHistory = [keyword, ...oldHistory]
    console.log(newHistory)
    // 保存到redux
    dispatch({
      type: 'search/history',
      payload: newHistory
    })
  }
}

export function clearHistories (): RootThunkAction {
  return async (dispatch) => {
    // 清空redux数据
    dispatch({
      type: 'search/clearHistories'
    })
  }
}

export function clearItemHistory (it: string): RootThunkAction {
  return async (dispatch, getState) => {
    const history = getState().search.searchHistory
    const newHistory = history.filter((item: string) => item !== it)
    console.log(newHistory, 'newHistory')
    dispatch({
      type: 'search/clearItemHistory',
      payload: newHistory
    })
  }
}

export function getSearchResult (
  q: string,
  page: number,
  per_page: number = 10
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<searchResult>>('/search', {
      params: {
        q,
        page,
        per_page
      }
    })
    console.log(res.data.data, 'res.data.data.results')
    if (res.data.data.results.length === 0) {
      Toast.show({
        content: '暂无数据!'
      })
      history.go(-1)
    } else {
      dispatch({
        type: 'search/result',
        payload: res.data.data
      })
    }
  }
}

export function claenSearchResult (): RootThunkAction {
  return async (dispatch) => {
    dispatch({
      type: 'search/clearResult',
      payload: {
        page: 1,
        per_page: 10,
        total_count: 0,
        results: []
      }
    })
  }
}
